import {
  Component,
  Input,
  HostBinding,
  Host,
  ContentChild,
  ElementRef,
} from '@angular/core';
import { RequiredValidator } from '@angular/forms';

import { FormDirective } from '../form.directive';

@Component({
  selector: 'fui-form-item',
  templateUrl: './form-item.component.html',
})
export class FormItemComponent {
  @HostBinding('class.fui-form-item') hostClass = true;

  @ContentChild(RequiredValidator) requiredValidator: RequiredValidator;

  /** Form label. */
  @Input() label: string;

  /** Label flex style. */
  @Input() labelFlex: string;

  /** Input flex style. */
  @Input() inputFlex: string;

  get required(): boolean | string {
    if (!this.requiredValidator) {
      return false;
    }
    return this.requiredValidator.required;
  }

  formErrorCount = 0;

  // flex样式会从fuiFormItem指令的input逐步退化到fuiForm指令的input
  get _labelFlex() {
    return this.labelFlex || this.form.labelFlex;
  }

  get _inputFlex() {
    return this.inputFlex || this.form.inputFlex;
  }

  constructor(
    @Host() private form: FormDirective,
    private elementRef: ElementRef,
  ) {}

  increFormError() {
    this.formErrorCount ++;
    this.updateHostClass();
  }

  decreFormError() {
    this.formErrorCount --;
    this.updateHostClass();
  }

  // 不能用HostBinding，因为是从子元素出发父元素，引起Angular check error。
  updateHostClass() {
    const element: HTMLElement = this.elementRef.nativeElement;
    const withErrorClass = 'fui-form-item-with-error';
    if (this.formErrorCount > 0) {
      element.classList.add(withErrorClass);
    } else {
      element.classList.remove(withErrorClass);
    }
  }

}
